<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;
use app\model\Campaign;
use app\model\Customer;
use app\model\Principal;

class Semunit extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function read(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semunit:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$search = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		if( in_array($sort, ['impression', 'clicks', 'cost', 'cash', 'rebate', 'copynumber', 'cpc', 'ctr', 'copycost']) ) {
			$sort = 's.'.$sort;
		} else {
			$sort = 'a.'.$sort;
		}

		array_push( $search, " s.companyId = {$request->sessInfo['companyId']} ");
		array_push( $where, ['a.companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['a.userType', '=', 1 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['a.bazaarId', '=',  $bazaarId ] );
		}

		$userId = $request->param('userId', '', 'trim');
		if($userId) {
			array_push( $where, ['a.userId', '=',  $userId ] );
		}
		
		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $where, ['a.customerid', '=',  $customerid ] );
		}

		$contact = $request->param('contact', '', 'trim');
		if($contact) {
			array_push( $where, ['a.contact', '=',  $contact ] );
		}

		$campaignId = $request->param('campaignId', '', 'trim');
		if($campaignId) {
			array_push( $where, ['a.campaignId', 'in',  $campaignId ] );
		}

		$status = $request->param('status', '', 'trim');
		if($status) {
			array_push( $where, ['a.status', '=',  $status ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			$time = cloud_datetime_format( $createTimeStart, $createTimeEnd, true);
			array_push( $search, " `s`.`datatime` BETWEEN {$time[0]} AND {$time[1]} ");
		} else {
			$time = cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true);
			array_push( $search, " `s`.`datatime` BETWEEN {$time[0]} AND {$time[1]} ");
		}
 	$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('semauthaccount');
			if($authaccount) {
				array_push( $where, ['a.userId', 'in',  $authaccount ] );
			}
		}
		$query = Db::table('cfg_adgroup')
		->alias('a')
		->field('a.id, a.userId, a.customerid, a.contact, a.bazaarId, a.status, a.maxPrice, a.campaignId, a.campaignName, a.adgroupId, a.adgroupName,
		  a.exactNegativeWords, a.negativeWords, a.datatime, a.ftypes, a.extend1, a.extend2,
		  sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
	  ->leftJoin('cfg_search s','a.adgroupId = s.adgroupid AND ' . implode(' AND ', $search))
		->where($where)
		->order($sort, $order)
		->group('a.adgroupId')
		->paginate($limit);

		$total = Db::table('cfg_adgroup')
		->alias('a')
		->field('sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
	  ->leftJoin('cfg_search s','a.adgroupId = s.adgroupid AND ' . implode(' AND ', $search))
		->where($where)
		->find();

		$total['impression'] = $total['impression'] ? $total['impression'] : 0;
		$total['clicks'] = $total['clicks'] ? $total['clicks'] : 0;
		$total['cost'] = $total['cost'] ? $total['cost'] : 0;
		$total['cash'] = $total['cash'] ? $total['cash'] : 0;
		$total['rebate'] = $total['rebate'] ? $total['rebate'] : 0;
		$total['cpc'] = $total['cpc'] ? $total['cpc'] : 0;
		$total['ctr'] = $total['ctr'] ? $total['ctr'] : 0;
		$total['copynumber'] = $total['copynumber'] ? $total['copynumber'] : 0;
		$total['copycost'] = $total['copycost'] ? $total['copycost'] : 0;

    $count = $query->total();
		$items = $query->items();
		foreach($items as &$value ) {
			$value['impression'] = $value['impression'] ? $value['impression'] : 0;
			$value['clicks'] = $value['clicks'] ? $value['clicks'] : 0;
			$value['cost'] = $value['cost'] ? $value['cost'] : 0;
			$value['cash'] = $value['cash'] ? $value['cash'] : 0;
			$value['rebate'] = $value['rebate'] ? $value['rebate'] : 0;
			$value['cpc'] = $value['cpc'] ? $value['cpc'] : 0;
			$value['ctr'] = $value['ctr'] ? $value['ctr'] : 0;
			$value['copynumber'] = $value['copynumber'] ? $value['copynumber'] : 0;
			$value['copycost'] = $value['copycost'] ? $value['copycost'] : 0;
			$exactNegativeWords = $value['exactNegativeWords'] ? unserialize($value['exactNegativeWords']) : [];
			$negativeWords = $value['negativeWords'] ? unserialize($value['negativeWords']) : [];
			$value['exactNegativeWords'] = $exactNegativeWords;
			$value['negativeWords'] = $negativeWords;
		}

		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items, 'total' => $total,
			'expand' => Expand::getList($request->sessInfo, 1),
		  'customer' => Customer::getList($request->sessInfo),
		  'principal' => Principal::getList($request->sessInfo),
			'bazaar' => Bazaar::getList($request->sessInfo, 1)];
	}

	/**
	* 查询账号创意
	*
	* @param tValue
	* @return
	*/
	public function getCampaign(Request $request) {
		$userid = $request->param('userid', '', 'trim');
		if( empty($userid)) {
			return ['code'=> 0, 'campaign'=> [] ];
		}
		return ['code'=> 0, 'campaign'=> Campaign::getList($request->sessInfo, $userid)];
	}

	/**
	* 单元执行地址
	*
	* @param tValue
	* @return
	*/
	private function updateAdgroup($parameter) {
		$request = doPostRequest('https://api.baidu.com/json/sms/service/AdgroupService/updateAdgroup', $parameter);
		if(empty($request)) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		$result = json_decode ($request, true);
		if(!isset($result['header']['desc'])){
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		if(!isset($result['header']['desc'])) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		return $result;
	}

	/**
	* 同步百度官方单元
	*
	* @param tValue
	* @return
	*/
	public function getCloud(Request $request) {
		if($this->hasPermission($request->sessInfo, 'semunit:cloud')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$userId = $request->param('userId', '', 'trim');
		if( empty($userId) ) {
			return ['code'=> 403, 'msg'=> '请选择要同步的账号!'];
		}

		$obj = Expand::getUserInfo($request->sessInfo, $userId, 1);
		if(!is_object($obj)) {
			return ['code'=> 403, 'msg'=> '数据异常,请稍后重试!'];
		}

    $campaignIds = [];
    $campaign = Db::table('cfg_campaign')->field('id, campaignId')->where('userId', $obj->userid)->select()->toArray();
		if(is_array($campaign)){
			foreach( $campaign as $value) {
			  array_push($campaignIds, $value['campaignId']);
			}
		}

		if( count($campaignIds) == 0 ) {
			return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
		}

		$result = $this->getAdgroup($obj, $campaignIds);
		if( $result['code'] == 403 ) {
			return json($result);
		}

		$campaignNameArray = Db::table('cfg_campaign')->field('campaignId, campaignName')->select()->toArray();
    $adgroupIdArray = [];
    if(is_array($result['data'])) {
			foreach($result['data'] as $value) {
				array_push($adgroupIdArray, $value['adgroupId']);
				$adgroupId = Db::table('cfg_adgroup')->where('companyId', $request->sessInfo['companyId'])
				  ->where('adgroupId', $value['adgroupId'])->value('id');
				$campaignName = cloud_get_array_value($campaignNameArray, $value['campaignId'], 'campaignId', 'campaignName', null);
				if($adgroupId) {
					Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupId'])->update([
						'maxPrice' => $value['maxPrice'],
						'datatime' => date('Y-m-d H:i:s'),
						'campaignName' => $campaignName,
						'contact' => $obj->contact,
						'customerid' => $obj->customerid,
						'adgroupName' =>  $value['adgroupName'],
						'negativeWords' => serialize($value['negativeWords']),
						'exactNegativeWords' => serialize($value['exactNegativeWords']),
						'status' => $value['status']
					]);
				} else {
					Db::name('cfg_adgroup')->insert([
					  'companyId' => $request->sessInfo['companyId'],
						'userType' => 1,
						'userId' => $obj->userid,
						'contact' => $obj->contact,
						'customerid' => $obj->customerid,
						'bazaarId' => $obj->bazaarId,
						'maxPrice' => $value['maxPrice'],
						'datatime' => date('Y-m-d H:i:s'),
						'campaignId' => $value['campaignId'],
						'campaignName' => $campaignName,
						'adgroupId' =>  $value['adgroupId'],
						'adgroupName' =>  $value['adgroupName'],
						'negativeWords' => serialize($value['negativeWords']),
						'exactNegativeWords' => serialize($value['exactNegativeWords']),
						'status' => $value['status']
					]);
				}
			}
			if(count($adgroupIdArray) > 0) {
				Db::table('cfg_adgroup')->where('companyId', $request->sessInfo['companyId'])->where('userId', $obj->userid)
					->whereNotIn('adgroupId', $adgroupIdArray)->delete();
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
	}

	/**
	 * 设置单元推广否定词
	 *
	 * @return
	 */
	public function setWords(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semunit:words')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'请选择要设置的单元!'];
		}

		$exactNegativeWordsArray = [];
		$exactNegativeWords = $request->param('exactNegativeWords', '', 'trim');
		$tempexactNegativeWordsArray = explode("\n", $exactNegativeWords);
		foreach( $tempexactNegativeWordsArray as $value  ) {
			$value = trim($value);
			if($value && !in_array($value, $exactNegativeWordsArray)) {
				array_push($exactNegativeWordsArray, $value);
			}
		}

    $negativeWordsArray = [];
		$negativeWords = $request->param('negativeWords', '', 'trim');
		$tempnegativeWordsArray = explode("\n", $negativeWords);
		foreach( $tempnegativeWordsArray as $value  ) {
			$value = trim($value);
			if($value && !in_array($value, $negativeWordsArray)) {
				array_push($negativeWordsArray, $value);
			}
		}

		$result = [];
		$beginTime = microtime(true);
		$query = Db::table('cfg_adgroup')->field('id, userId, adgroupId, adgroupName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('adgroupId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateAdgroup(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'adgroupTypes'=>[
								[
									"adgroupId"=> $value['adgroupId'],
									"negativeWords"=> $negativeWordsArray,
									"exactNegativeWords"=> $exactNegativeWordsArray,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						$negativeWords = isset($response['body']['data'][0]['negativeWords']) ? $response['body']['data'][0]['negativeWords'] : [];
						$exactNegativeWords = isset($response['body']['data'][0]['exactNegativeWords']) ? $response['body']['data'][0]['exactNegativeWords'] : [];
						Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupId'])->update(['exactNegativeWords' => serialize($exactNegativeWords), 'negativeWords' => serialize($negativeWords)]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索单元报告', '设置单元推广否定关键词, ', 0, null);
						array_push($result, '<i class="el-message__icon el-icon-success"></i><span style="vertical-align:top;">['.$value['adgroupName'].'] 操作成功.</span>');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '<i class="el-message__icon el-icon-error"></i><span style="vertical-align:top;">['.$value['adgroupName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] . '</span>');
					}
				}
			}
		}
    return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=> $result]);
	}

	/**
	 * 设置单元每日预算
	 *
	 * @return
	 */
	public function setmaxPrice(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semunit:maxPrice')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];
		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}


		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'请选择要设置的单元!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$maxPrice = $request->param('maxPrice', '', 'trim');
		$query = Db::table('cfg_adgroup')->field('id, userId, adgroupId, adgroupName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('adgroupId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateAdgroup(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'adgroupTypes'=>[
								[
									"adgroupId"=> $value['adgroupId'],
									"maxPrice"=> $maxPrice,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupId'])->update(['maxPrice' => $maxPrice]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索单元报告', '设置单元出价, ' . $maxPrice . '元', 0, null);
						array_push($result, '['.$value['adgroupName'].'] 操作成功.');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '['.$value['adgroupName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}

	/**
	 * 设置单元状态
	 *
	 * @return
	 */
	public function setPause(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'semunit:pause')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$selectId = $request->param('selectId/a', '', 'trim');
		if( count($selectId) == 0 ) {
			return ['code'=> 403, 'msg'=> '请选择要设置的单元!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$pause = $request->param('pause/d', '', 'trim');
		$query = Db::table('cfg_adgroup')->field('id, userId, campaignId, adgroupId, adgroupName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $selectId)->group('adgroupId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 1);
				if(is_object($obj)) {
					$response = $this->updateAdgroup(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'adgroupTypes'=>[
								[
									"adgroupId"=> $value['adgroupId'],
									"pause"=> $pause,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						$status = 32;
						if($pause === 0) {
							$campaignIdArr = [];
							array_push($campaignIdArr, $value['campaignId']);
							$getAdgroup = $this->getAdgroup($obj, $campaignIdArr);
							if( isset($getAdgroup['data'][0]['status'])) {
								$status = $getAdgroup['data'][0]['status'];
							}
				    }
						Db::name('cfg_adgroup')->where('adgroupId', $value['adgroupId'])->update(['status' => $status]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '搜索单元报告', '设置单元状态, ' . $pause, 0, null);
						array_push($result, '['.$value['adgroupName'].'] 操作成功.');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '['.$value['adgroupName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}

	/**
	* 读取最新单元数据
	*
	* @param tValue
	* @return
	*/
	private function getAdgroup($obj, $adgroupId) {
		$response = doPostRequest('https://api.baidu.com/json/sms/service/AdgroupService/getAdgroup', json_encode([
			'header'=>['username'=> $obj->username, 'password'=> $obj->password, 'token'=>$obj->token],
			'body'=> [
        "ids"=> $adgroupId,
        "idType"=> 3,
        "adgroupFields"=>[
            "adgroupId",
            "adgroupName",
            "campaignId",
            "pause",
            "maxPrice",
            "negativeWords",
            "exactNegativeWords",
            "status"
        ]
			]
		]));

		if(empty($response)) {
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		$result = json_decode ($response, true);
		if(!isset($result['header']['desc'])){
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		if(!isset($result['header']['desc'])) {
			return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
		}

		if($result['header']['desc'] == 'failure') {
			$tempMessage  = explode('sn:', $result['header']['failures'][0]['message']);
			return ['code'=> 403, 'msg'=> 'code: ' . $result['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] ];
		}

		if( isset($result['body']['data'])) {
			return ['code'=> 0, 'data'=> $result['body']['data'] ];
		}

		return ['code'=> 403, 'msg'=> 'network anomaly detection.!'];
	}

}
